import React, {Component} from 'react';
import './GongJu.css'
import {store} from "../redux/count_gong_ju.js";

class GongJu extends Component {
    state = {
        num: store.getState(), //读取数据
        select_val: '1',
    }

    componentDidMount() {
        //订阅数据变化通知
        store.subscribe(()=>{
            this.setState({
                num: store.getState() //同步数据
            })
        })
    }

    /**
     * 下拉框修改事件
     * @param e
     */
    selectChange = (e) => {
        this.setState({
            select_val: e.target.value
        })
    }
    //相加
    add = () => {
        //传送数据
        store.dispatch({
            type: '加',
            data: this.state.select_val-0
        })
    }

    //相减
    subtract = () => {

        store.dispatch({
            type: '减',
            data: this.state.select_val-0
        })
    }
    //当前求和为奇数再加
    oddAdd = () => {
        if (this.state.num % 2 !== 0) {
            store.dispatch({
                type: '加',
                data: this.state.select_val-0
            })
        }
    }
    /**
     * 异步加 一般这里的数据使用异步获取
     */
    asyncAdd = () => {
        store.dispatch((dispatch)=>{
            setTimeout(()=>{
                dispatch({
                    type: '加',
                    data: this.state.select_val-0
                })
            },500)
        })
    }

    render() {
        return (
            <div>
                <h3>获取store的数据：{store.getState()}</h3>
                <div>
                    <select className={"input"} value={this.state.select_val} onChange={this.selectChange}>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                    </select>
                    <button onClick={this.add}>加</button>
                    &nbsp;
                    <button onClick={this.subtract}>减</button>
                    &nbsp;
                    <button onClick={this.oddAdd}>当前求和为奇数再加</button>
                    &nbsp;
                    <button onClick={this.asyncAdd}>异步加</button>
                </div>
            </div>
        );
    }
}

export default GongJu;